<?php

/**
 * Created by PhpStorm.
 * User: evan
 * Date: 2017/3/9
 * Time: 上午1:00
 */

require_once APPPATH."libraries/wxpay/WxPay.JsApiPay.php";
require_once APPPATH."libraries/wxpay/lib/WxPay.Api.php";
require_once APPPATH."libraries/wxpay/lib/WxPay.Notify.php";

class Finance extends MY_M_Controller
{
    /**
     * 微信充值
     */
    public function index()
    {
    	//$this->isWeiXinLogin();
    	
    	$this->load->view('m/finance/weixin');
    }
    
	public function weixin_pay()
	{
		$uid     = (int)$this->input->get_post('uid');
		$amount  = (int)$this->input->get_post('amount');
		
		if (!$uid || !$amount)
		{
			return sur(array(), 100002);
		}
		
		$this->load->model('finance/Model_finance_payment', 'fp');
		$record_rs = $this->fp->record($uid, 5, $amount, $amount, '用户充值', 0);
			
		$tools = new JsApiPay();
		$input = new WxPayUnifiedOrder();
			
		$input->SetBody("美时美客");
		$input->SetAttach("");
		$input->SetOut_trade_no(WxPayConfig::MCHID.time().$record_rs['data']['pid']);
		$input->SetTotal_fee($amount * 100);
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("");
		$input->SetNotify_url("http://m.shikee.tv/finance/pay_success");
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($_SESSION['user']['openid']);
			
		$order = WxPayApi::unifiedOrder($input);
		
		$jsApiParameters = $tools->GetJsApiParameters($order);
		
		$this->load->view('m/finance/weixin_pay', array('jsApiParameters'=>$jsApiParameters));
	}
	
	public function pay_success()
	{
		$notify = new PayNotifyCallBack();
		$notify->Handle(false);
	}
}


class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);

		if(array_key_exists("return_code", $result)
				&& array_key_exists("result_code", $result)
				&& $result["return_code"] == "SUCCESS"
				&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		$notfiyOutput = array();

		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}

		if($data['return_code']=='SUCCESS')
		{
			$data['out_trade_no'] = substr($data['out_trade_no'], 20);
			
			$ci = get_instance();
			$ci->load->model('finance/Model_finance_payment', 'fp');
				
			$order_info = $ci->fp->getOne(array('is_paid'=>'0', 'pid'=>$data['out_trade_no']));
				
			if($order_info)
			{
				$set_data = array
				(
						'is_paid'=>'1',
						'pay_time'=>date('Y-m-d H:i:s'),
						'out_order_id'=>$data['transaction_id'],
						'callback_data'=>json_encode($data)
				);
				$ci->fp->update($set_data, array('is_paid'=>'0', 'pid'=>$data['out_trade_no']));
			
				$ci->load->model('finance/Model_finance_base_log', 'fbl');
				$income_rs = $ci->fbl->income
				(
						$order_info['uid'],
						$order_info['real_amount']*10,
						CURRENCY_SGD,
						$order_info['pid'],
						'币种转换收入',
						'INCOME',
						FINANCE_BUSINESS_TRANS,
						'充值'
				);
			
				if (200 != $income_rs['status'])
				{
					return false;
				}
			}
			return false;
		}

		return true;
	}
}